<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
	<meta charset="UTF-8">
    <title>入库登记单页面</title>
    <link rel="stylesheet"  href="/bootstrap/bootstrap-5.3.3-dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="/css/stock/h/Warehouse_Receving_Registration_sub.css" />
    <style type="text/css">
    
    </style>
</head>
<body style="padding: 15px 50px;background-color: #eeeeee;">
	<div class="panel-heading hhead">
		<nav aria-label="breadcrumb">
		  <ol class="breadcrumb">
		  	<span style="color: blue;">您正在做的业务是：</span>
		    <li class="breadcrumb-item"><a href="#">库存管理</a></li>
		    <li class="breadcrumb-item"><a href="#">入库管理</a></li>
		    <li class="breadcrumb-item active" aria-current="page">入库登记</li>
		  </ol>
		</nav>
	</div>
    <div style="margin-bottom: 2px">
        <div style="display: inline;margin-left: 89%;">
            <button type="button" class="btn btn-primary"  id="submit">提交</button>
            <button type="button" class="btn btn-primary" id="back">返回</button>
        </div>
    </div> <!-- 此div改用栅格来做 -->
    <div id="designListBox">
        <div style="text-align: center">
            <h3>入库单</h3>
        </div>
        <div style="padding: 30px">
           <table class="tbl1">
               <tr>
                   <td class="col1">入库单编号：</td>
                   <td class="col2" id="gatherId"></td>
               </tr>
               <tr>
                   <td class="col1">入库理由：</td>
                   <td class="col2" id="reason"></td>
                   <td class="col1">入库详情理由：</td>
                   <td class="col2" id="reasonexact"></td>
               </tr>
               
           </table>

            <table class="table table-bordered" style="margin: 15px auto;">
                <thead>
                    <tr>
                        <th>产品编号</th><th>产品名称</th><th>库存名称</th>
                        <th>当前库存数量</th><th>应入库件数</th><th>已入库件数</th>
                        <th>本次入库数量</th>
                    </tr>
                </thead>
                <tbody id="template">

                </tbody>
            </table>

            <table class="tbl3">
                <tr>
                    <td class="col1">应入库总件数：</td>
                    <td class="col2" id="Should"></td>
                    <td class="col1">已入库总件数：</td> <td class="col2" id="already"></td>
                </tr>
                <tr>
                    <td class="col1">应入库总成本：</td>
                    <td class="col2" id="ShouldPrice"></td>
                    <td class="col1">已入库总成本：</td> <td class="col2" id="alreadyPrice"></td>
                </tr>
                <tr>
                    <td class="col1">登记人：</td>
                    <td class="col2" id="register"></td>
                    <td class="col1">登记时间：</td> <td class="col2" id="registerTime">系统时间</td>
                </tr>
            </table>
        </div>
    </div>
    <script type="text/javascript" src="/js/jquery-3.7.0.min.js"></script>
    <script type="text/javascript" src="/bootstrap/bootstrap-5.3.3-dist/js/bootstrap.bundle.min.js"></script>
    <script type="text/javascript" src="/js/common.js"></script>
    <script type="text/javascript">
        $(function (){
            // 初始化数据
            ItemApprovalTable();
            $("#back").on("click",function (){
                window.location.href="/s-gather/Warehouse_Receiving_Registration";
            })
            $("#submit").on("click",function (){
                //本次出库数量等于应出库件数
                // for (let i = 0; i < $("#template tr").length; i++) {
                //     let num =parseInt($("#template tr").eq(i).find(".num-input").val());
                //     let should =parseInt($("#template tr").eq(i).find(".should").text());
                //     //获取当前库存数量  本次出库数量<=当前库存数量
                //     let current =parseInt($("#template tr").eq(i).find(".current").text());
                //     if (num != should || num > current) {
                //         alert("库存总数量不足或出库数量有误");
                //         return;
                //     }
                // }

                //获取入库单编号
                let gatherId = $("#gatherId").text();
                //获取入库总件数
                let should = $("#Should").text();
                let data = [];
                data.push({
                    //入库单编号
                    gatherId: gatherId,
                    //确认入库总件数
                    gatheredAmountSum: should,
                })
                let rows = $("#template tr");
                for (let i = 0; i < rows.length; i++) {
                    let row = rows[i];
                    let productId = $(row).find("td:eq(0)").text();
                    let gatheredAmount= $(row).find("td:eq(6)").find("input").val();
                    let obj = {
                        productId: productId, //产品编号
                        gatheredAmount: gatheredAmount, //本次入库数量
                    }
                    data.push(obj);
                }
                data=JSON.stringify(data);
                console.log("登记所需数据："+data);
                //修改入库表和入库明细表的入库标志和确认入库总件数和入库登记审核标志
                $.ajax({
                    url: "/s-gather/recevingRegistration",
                    type: "POST",
                    data:  data,
                    contentType: "application/json",
                    dataType: "json",
                    success: function (flag) {
                        if (flag){
                            alert("本次登记成功，需要复核！");
                            window.location.href = "/s-gather/Warehouse_Receiving_Registration";
                        }else{
                            alert("本次登记失败！");
                        }
                    },
                    error: function (e) {
                    }
                })
            })
        })
        function ItemApprovalTable(){
            let id = sessionStorage.getItem("id");
            $("#id").val(id);
            $.ajax({
                url: "/s-gather/ItemApprovalTable?id="+id,
                type: "GET",
                dataType: "json",
                success: function (data) {
                    // console.log(data);
                    if (data.errCode == "1") {
                        alert(data.errMsg)
                    } else {
                        $("#gatherId").text(data.gatherId);
                        $("#reason").text(data.reason);
                        $("#reasonexact").text(data.reasonexact);
                        $("#gatherId").attr("value",data.id)
                        $("#ShouldPrice").text(data.costPriceSum);
                        $("#register").text(data.register)
                        $("#registerTime").text(data.registerTime);
                        initialTemplate(data.id);
                    }
                }
            })
        }
        function initialTemplate(parentId){
            $.ajax({
                url: "/s-gather/initialTemplate?id="+parentId,
                type: "GET",
                dataType: "json",
                success: function (data) {
                    // console.log(data);
                    if (data.errCode == "1") {
                        alert(data.errMsg)
                    } else {
                        let template = $("#template");

                        // 清空表格
                        template.empty();
                        // 遍历数据并添加到表格中
                        data.forEach(function (item, index) {

                            let w=  Add(item.productId);

                            let amount =AddAmount(item.productId);
                            let row = $("<tr>");
                            row.append($("<td>").text(item.productId));
                            row.append($("<td>").text(item.productName));
                            row.append($("<td>").text(w))
                            row.append($("<td>").text(amount).addClass("current"))
                            row.append($("<td>").text(item.gatheredAmount).addClass("should"));
                            row.append($("<td>").text("0").append($("<input>").attr("type","hidden").attr("value",item.costPrice)));
                            row.append($("<td>").append($("<input>").addClass("num-input").attr("type","number")));
                            template.append(row);

                        })
                        //初始化应出库总件数和已出库总件数
                        initialTotalSum();
                        initalalreadyPrice();
                    }
                }
            })
        }

        function initialTotalSum(){
            // 初始化总和变量
            let totalOutbound = 0;
            let totalAlready = 0;
            // 选择表格中tbody下所有的tr元素，然后找到每个tr里面的第四列（索引为3，因为索引从0开始计数）
            $('#template tr').each(function () {
                let num = parseInt($(this).find('td').eq(4).text());
                let num2 = parseInt($(this).find('td').eq(5).text());
                totalOutbound += num;
                totalAlready += num2;
            });

            $("#Should").text(totalOutbound);
            $("#already").text(totalAlready);
        }
        function Add(productId){
            let warehouseName ="";
            $.ajax({
                url: "/s-warehouse-setting/getWarehouseName",
                type: "POST",
                async: false,
                data: productId,
                contentType: "application/json",
                dataType: "json",
                success: function (data) {
                    // console.log("库房名称：" + data.warehouseName);
                    warehouseName = data.warehouseName;
                }
                ,error:function (e){

                }
            })
            return warehouseName;
        }
        function AddAmount(productId){
            let amount = 0;
            //得到当前存储量
            $.ajax({
                url: "/s-gather/initialAmount",
                type: "POST",
                async: false,
                data: productId,
                contentType: "application/json",
                dataType: "json",
                success: function (data) {
                    amount= data.sCell.amount;
                },
                error: function (e) {
                    console.log(e);
                }
            })
            return amount;
        }
        function initalalreadyPrice(){
            //设置已入库总成本
            let alreadyPrice = 0;
            $("#template tr").each(function (){
                // 获取已入库数量
                let already = $(this).find("td").eq(5).text();
                let price = $(this).find("td").eq(5).find("input").val();
                alreadyPrice +=already* price;
                $("#alreadyPrice").text(alreadyPrice);
            })
        }
    </script>
</body>
</html>
